package copyengine.utils.polygon {
    import flash.geom.Point;

    /**
     * 矢量三角形, 用于构成CEVectorPolygon
     */
    public class CEVectorTriangle {
        private var mPA:Point;
        private var mPB:Point;
        private var mPC:Point;

        private var mV0:Point;
        private var mV1:Point;
        private var mV2:Point;

        private var mDot00:Number;
        private var mDot01:Number;
        private var mDot11:Number;

        private var mInvDenom:Number;

        public function CEVectorTriangle(_pa:Point, _pb:Point, _pc:Point) {
            mPA = _pa;
            mPB = _pb;
            mPC = _pc;

            mV0 = new Point(mPC.x - mPA.x, mPC.y - mPA.y);
            mV1 = new Point(mPB.x - mPA.x, mPB.y - mPA.y);
            mV2 = new Point();

            mDot00 = dot(mV0, mV0);
            mDot01 = dot(mV0, mV1);
            mDot11 = dot(mV1, mV1);

            mInvDenom = 1 / (mDot00 * mDot11 - mDot01 * mDot01);
        }

        public function get a():Point {return mPA;}

        public function get b():Point {return mPB;}

        public function get c():Point {return mPC;}

        public function hitTestPoint(_x:Number, _y:Number):Boolean {
            mV2.x = _x - mPA.x;
            mV2.y = _y - mPA.y;
            var dot02:Number = dot(mV0, mV2);
            var dot12:Number = dot(mV1, mV2);
            var u:Number = (mDot11 * dot02 - mDot01 * dot12) * mInvDenom;
            var v:Number = (mDot00 * dot12 - mDot01 * dot02) * mInvDenom;
            return (u >= 0) && (v >= 0) && (u + v <= 1.0)
        }

        public function randomPointInTriangle(_result:Point = null):Point {
            if (_result == null) {
                _result = new Point();
            }
            //P = (1 - sqrt(r1)) * A + (sqrt(r1) * (1 - r2)) * B + (sqrt(r1) * r2) * C
            var r1:Number = Math.random();
            var r2:Number = Math.random();
            _result.x = (1 - Math.sqrt(r1)) * mPA.x + (Math.sqrt(r1) * (1 - r2)) * mPB.x + (Math.sqrt(r1) * r2) * mPC.x;
            _result.y = (1 - Math.sqrt(r1)) * mPA.y + (Math.sqrt(r1) * (1 - r2)) * mPB.y + (Math.sqrt(r1) * r2) * mPC.y;
            return _result;
        }


        private function dot(_a:Point, _b:Point):Number {return (_a.x * _b.x + _a.y * _b.y);}
    }
}
